package models;

import java.sql.ResultSet;
import system.Model;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import system.DbConnection;

/**
 * Class Barang
 * @author Rezan Achmad
 */
public class Barang extends Model {

    public static final String IMAGE_DEFAULT = "upload/not_defined.gif";
    public int id;
    public int kategori_id;
    public String nama;
    public String path_gambar;
    public String deskripsi;
    public int harga_satuan;
    public int jumlah;
    public int poin;
    public int berat; // Dalam Gram

    @Override
    public boolean add() {
        String sql =
                "INSERT INTO `barang`(`kategori_id`, `nama`, `path_gambar`, `deskripsi`, `harga_satuan`, `jumlah`, `poin`, `berat`)"
                + "VALUES(" + kategori_id + ", '" + nama + "', '" + path_gambar + "', '" + deskripsi + "', " + harga_satuan + ", " + jumlah + ", " + poin + ", " + berat + ")";
        try {
            getStatement().executeUpdate(sql);
            
            // Log
            Log.add(sql);
        } catch (SQLException ex) {
            Logger.getLogger(Barang.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

        return true;
    }

    public boolean update() {
        String sql =
                "UPDATE `barang` SET `kategori_id` = " + kategori_id + ", "
                + "`nama` = '" + nama + "', "
                + "`path_gambar` = '" + path_gambar + "', "
                + "`deskripsi` = '" + deskripsi + "', "
                + "`harga_satuan` = " + harga_satuan + ", "
                + "`jumlah` = " + jumlah + ", "
                + "`poin` = " + poin + ", "
                + "`berat` = " + berat + " "
                + "WHERE `id` = " + id + "";
        try {
            getStatement().executeUpdate(sql);
            
            // Log
            Log.add(sql);
        } catch (SQLException ex) {
            Logger.getLogger(Barang.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

        return true;
    }

    public String getCategoryName() {
        String retVal = "";

        String sql =
                "SELECT * FROM `kategori_barang` WHERE `id`=" + kategori_id;
        try {
            ResultSet rs = DbConnection.getStatement().executeQuery(sql);
            if (rs.next()) {
                retVal = rs.getString("nama");
            }
        } catch (SQLException ex) {
            Logger.getLogger(Barang.class.getName()).log(Level.SEVERE, null, ex);
        }

        return retVal;
    }

    public int getCountBySql(String sql) {
        try {
            ResultSet rs = DbConnection.getStatement().executeQuery(sql);
            if (rs.next()) {
                return rs.getInt("count");
            }
        } catch (SQLException ex) {
            Logger.getLogger(Barang.class.getName()).log(Level.SEVERE, null, ex);
        }

        return 0;
    }
    
    public int getCount() {
        return getCountBySql("SELECT COUNT(`id` ) AS `count` FROM `barang`");
    }
    
    public int getCount(String keywords) {
        return getCountBySql("SELECT COUNT(`id` ) AS `count` FROM `barang` WHERE `nama` LIKE '%" + keywords + "%'");
    }
    
    public int getCountByKategori(int kategoriId) {
        return getCountBySql("SELECT COUNT(`id` ) AS `count` FROM `barang` WHERE `kategori_id`='" + kategoriId + "'");
    }
    
    public int getCountByKategori(String keywords, int kategoriId) {
        return getCountBySql("SELECT COUNT(`id` ) AS `count` FROM `barang` WHERE `nama` LIKE '%" + keywords + "%' AND `kategori_id`='" + kategoriId + "'");
    }

    public static Barang getInstance() {
        return new Barang();
    }
    
    public static Barang get(int id) {
        Barang barang = new Barang();

        String sql =
                "SELECT * FROM `barang` WHERE `id`=" + id;
        try {
            ResultSet rs = DbConnection.getStatement().executeQuery(sql);
            if (rs.next()) {
                barang.setAttributes(rs);
            } else {
                return null;
            }
        } catch (SQLException ex) {
            Logger.getLogger(Barang.class.getName()).log(Level.SEVERE, null, ex);
        }

        return barang;
    }

    public static boolean delete(int id) {
        String sql =
                "DELETE FROM `barang` WHERE `id`=" + id;
        try {
            // Delete
            DbConnection.getStatement().executeUpdate(sql);
            
            // Log
            Log.add(sql);
        } catch (SQLException ex) {
            Logger.getLogger(Barang.class.getName()).log(Level.SEVERE, null, ex);
        }

        return false;
    }

    public static boolean getAll(ArrayList<Barang> listBarang, ArrayList<String> listNamaKategori) {
        String sql =
                "SELECT * FROM `barang` JOIN `kategori_barang` ON `barang`.`kategori_id`=`kategori_barang`.`id`";
        try {
            ResultSet rs = DbConnection.getStatement().executeQuery(sql);
            Barang barang;
            while (rs.next()) {
                barang = new Barang();
                barang.setAttributes(rs);
                listBarang.add(barang);
                listNamaKategori.add(rs.getString("kategori_barang.nama"));
            }
            return true;
        } catch (SQLException ex) {
            Logger.getLogger(Barang.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    /**
     * Mengambil seluruh barang.
     * @return Mengamblikan list Barang jika ditemukan atau null jika tidak ditemukan.
     */
    public static ArrayList<Barang> getAll() {
        String sql = "SELECT * FROM `barang`";
        return Barang.getAllBySql(sql);
    }

    /**
     * Mengambil seluruh barang dengan offset dan count tertentu
     * @param offset
     * @param count
     * @return Mengamblikan list Barang jika ditemukan atau null jika tidak ditemukan.
     */
    public static ArrayList<Barang> getAll(int offset, int count) {
        String sql = "SELECT * FROM `barang` LIMIT " + offset + "," + count;
        return Barang.getAllBySql(sql);
    }
    
    public static ArrayList<Barang> getAll(String keywords, int offset, int count) {
        String sql = "SELECT * FROM `barang` WHERE `nama` LIKE '%" + keywords + "%' LIMIT " + offset + "," + count;
        return Barang.getAllBySql(sql);
    }
    
    public static ArrayList<Barang> getAllByCategory(int kategoriId) {
        String sql = "SELECT * FROM `barang` WHERE `kategori_id` = " + kategoriId;
        return Barang.getAllBySql(sql);
    }
    
    public static ArrayList<Barang> getAllByCategory(int kategoriId, int offset, int count) {
        String sql = "SELECT * FROM `barang` WHERE `kategori_id` = '" + kategoriId + "' LIMIT " + offset + "," + count;
        return Barang.getAllBySql(sql);
    }
    
    public static ArrayList<Barang> getAllByCategory(String keywords, int kategoriId, int offset, int count) {
        String sql = "SELECT * FROM `barang` WHERE `nama` LIKE '%" + keywords + "%' AND `kategori_id` = '" + kategoriId + "' LIMIT " + offset + "," + count;
        return Barang.getAllBySql(sql);
    }
    
    /**
     * Mengambil seluruh barang berdasarkan query SQL.
     * @param sql Query SQL.
     * @return Mengamblikan list Barang jika ditemukan atau null jika tidak ditemukan.
     */
    public static ArrayList<Barang> getAllBySql(String sql) {
        try {
            // Execute Query
            ResultSet rs = DbConnection.getStatement().executeQuery(sql);

            // Check Result
            if (!rs.next()) {
                return null;
            }

            // Init list and temporay object
            ArrayList<Barang> barangs = new ArrayList<Barang>();
            Barang barang;

            // Iterate and add barang to list
            do {
                barang = new Barang();
                barang.setAttributes(rs);
                barangs.add(barang);
            } while (rs.next());

            return barangs;
        } catch (SQLException ex) {
            Logger.getLogger(Barang.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * Set atribut Barang.
     * @param rs Result Set dari query database.
     * @throws SQLException 
     */
    @Override
    public void setAttributes(ResultSet rs) throws SQLException {
        id = rs.getInt("barang.id");
        kategori_id = rs.getInt("barang.kategori_id");
        nama = rs.getString("barang.nama");
        path_gambar = rs.getString("barang.path_gambar");
        deskripsi = rs.getString("barang.deskripsi");
        harga_satuan = rs.getInt("barang.harga_satuan");
        jumlah = rs.getInt("barang.jumlah");
        poin = rs.getInt("barang.poin");
        berat = rs.getInt("berat");
    }

    @Override
    public boolean validate() {
        return true;
    }

    @Override
    public void initAttributesLabel() {
    }
}
